from colorama import Fore

from ..core import Tabulation, Constant
from ..ui import Icon
import keyboard


class CheckBox(Tabulation):
    def __init__(self, option):
        super().__init__(option)
        self.option = option

    def render(self, index):
        assert not type(self.icon) == str or 'icon' not in self.option.keys(), f"{Fore.RED}option set Icon is err"
        i = 0
        if 'icon' not in self.option.keys():
            self.icon = Icon.BRACKETS
        self.__fill_data()
        temp_data = self.data if self.page_size == 0 else self.pager(self.data, self.page_num, self.page_size)['data']
        print(f'{self.msg_color}?', f'{self.msg}:', f'{temp_data[index]["name"]}')
        for item in temp_data:
            if item['checked'] and i == index:
                print(f'{self.msg_color}{self.icon[1]}', f"{self.data_color}{item['name']}")
                self.current_value = item
            elif i == index:
                print(f'{self.msg_color}{self.icon[0]}', f"{self.data_color}{item['name']}")
                self.current_value = item
            elif item['checked']:
                print(f'{self.msg_color}{self.icon[1]}', f"{item['name']}")
            else:
                print(f'{self.msg_color}{self.icon[0]}', f"{item['name']}")
            i += 1
        if self.page_size != 0:
            res = self.pager(self.data, self.page_num, self.page_size)
            print(f'上一页(←)   {res["page_num"]}/{res["total_page_num"]}   下一页(→)')
            self.data_len = len(temp_data)

    def __fill_data(self):
        for item in self.data:
            if 'checked' not in item.keys():
                item['checked'] = False

    def __handle_space(self):
        self.current_value['checked'] = bool(1 - self.current_value['checked'])
        self.clear_screen()
        self.render(self.index)

    def run(self):
        self.render(0)
        keyboard.add_hotkey(Constant.DOWN, self.handle_down)
        keyboard.add_hotkey(Constant.UP, self.handle_up)
        keyboard.add_hotkey(Constant.SPACE, self.__handle_space)
        if self.page_size != 0:
            keyboard.add_hotkey(Constant.LEFT, self.handle_left)
            keyboard.add_hotkey(Constant.RIGHT, self.handle_right)
        keyboard.wait(Constant.CTRL)
        self.handle_off()
        return [{f'{self.name}': item['name']} for item in self.data if item['checked']]
